package com.msoe.core.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.msoe.utils.Utilities;

public class Database 
{
	private static Database instance;
	private Connection connection;
	
	private Database()
	{
		this.initDataAccess();
	}
	
	/**
	 * Returns the instance of the UserDatabase class so it can be worked with.
	 * @return An instance of the UserDatabase class.
	 */
	public static Database getInstance()
	{
		if(instance == null) instance = new Database();
		
		return instance;
	}
	
	/**
	 * Gives access to the users database.
	 */
	private void initDataAccess()
	{
		try
		{
			Class.forName("org.postgresql.Driver");
			connection = DriverManager.getConnection(Utilities.getConnectionURL(), Utilities.getDatabaseUsername(), Utilities.getDatabasePassword());
			
			connection.setAutoCommit(false);
		}
		catch(Exception e)
		{
			throw new DatabaseException(e);
		}
	}
	
	public Connection getConenction()
	{
		return this.connection;
	}
	
	/**
	 * Closes the database connection.
	 */
	public void closeConnection()
	{
		try 
		{
			connection.close();
		} 
		catch (SQLException e) 
		{
			// Re-throw as a database exception
			throw new DatabaseException(e);
		}
	}
}
